#!/bin/bash

# AIDE 数据卷目录快速修复脚本
# 解决 Ubuntu 服务器上的卷挂载错误

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================"
echo -e "AIDE 数据卷目录修复工具"
echo -e "=======================================${NC}"
echo ""

echo -e "${BLUE}📁 创建数据持久化目录...${NC}"

# 停止可能运行的服务
echo "停止现有服务..."
docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml down 2>/dev/null || true

# 创建系统级数据目录
echo "创建 /var/lib/aide 目录..."
sudo mkdir -p /var/lib/aide/postgres
sudo mkdir -p /var/lib/aide/redis

# 设置正确的权限
echo "设置目录权限..."
sudo chown -R 999:999 /var/lib/aide/postgres  # PostgreSQL 容器用户ID
sudo chown -R 999:999 /var/lib/aide/redis     # Redis 容器用户ID
sudo chmod -R 755 /var/lib/aide

# 创建项目本地目录
echo "创建项目本地目录..."
mkdir -p ./database/backup
mkdir -p ./backend/uploads
mkdir -p ./logs
mkdir -p ./nginx/logs
mkdir -p ./ssl

# 设置本地目录权限
chmod -R 755 ./database/backup
chmod -R 755 ./backend/uploads
chmod -R 755 ./logs
chmod -R 755 ./nginx/logs
chmod -R 755 ./ssl

echo -e "${GREEN}✅ 所有目录已创建完成${NC}"
echo ""

echo -e "${BLUE}📋 创建的目录列表:${NC}"
echo "系统数据目录:"
echo "  - /var/lib/aide/postgres (PostgreSQL 数据)"
echo "  - /var/lib/aide/redis (Redis 数据)"
echo ""
echo "项目本地目录:"
echo "  - ./database/backup (数据库备份)"
echo "  - ./backend/uploads (文件上传)"
echo "  - ./logs (应用日志)"
echo "  - ./nginx/logs (Nginx 日志)"
echo "  - ./ssl (SSL 证书)"
echo ""

echo -e "${BLUE}🔍 验证目录权限...${NC}"
echo "PostgreSQL 数据目录:"
ls -la /var/lib/aide/postgres 2>/dev/null || echo "  目录为空（正常）"
echo "Redis 数据目录:"
ls -la /var/lib/aide/redis 2>/dev/null || echo "  目录为空（正常）"
echo ""

echo -e "${GREEN}🎉 目录修复完成！${NC}"
echo ""
echo -e "${YELLOW}💡 接下来的步骤:${NC}"
echo "1. 确保 .env.prod 文件已正确配置"
echo "2. 运行部署命令:"
echo "   sudo docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml --env-file .env.prod up -d"
echo ""
echo -e "${BLUE}========================================"
echo -e "修复完成"
echo -e "=======================================${NC}"
